import axios from 'axios'
import qs from 'qs'
import { ElMessage } from 'element-plus'
import { API_DOMAIN, API_HALOLIVE } from './configData/config'
import { getToken, getShopInfo } from './auth'

axios.defaults.headers = {
  'X-Requested-With': 'XMLHttpRequest',
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Method': 'POST,GET'
}
const beforeAlterList = ['beforeAlterFirst', 'beforeAlterTwo', 'beforeAlterThree'] // 存储的列表字段名，在数组中，才会记录日志
const service = axios.create({
  baseURL: API_DOMAIN, // api 的 base_url  // mp.jddmoto.com/admin
  timeout: 60000, // request timeout
  transformRequest: [
    function (data) {
      // `transformRequest` 允许在向服务器发送前，修改请求数据
      // 只能用在 'PUT', 'POST' 和 'PATCH' 这几个请求方法
      // if (data) { data['platform'] = platformList2['OSS']; }
      return qs.stringify(data)
    }
  ]
})

// request interceptor
service.interceptors.request.use(
  (config) => {
    const token = getToken()
    const shopId = getShopInfo() && JSON.parse(getShopInfo() as any)?.id
    const userInfo = localStorage.getItem('userInfo') && JSON.parse(localStorage.getItem('userInfo') as any)
    if (token) {
      config.headers.token = token || ''
      config.headers.userId = config.params?.userId || config.data?.userId || ''
    }
    if (config.method === 'get') {
      config.headers = {
        // ...config.headers,
        'Content-type': 'application/x-www-form-urlencoded'
      }
      config.params = config.params || {}
      config.params = {
        token,
        bundleId: API_HALOLIVE,
        shopId,
        belongId: shopId,
        uid: userInfo?.uid,
        userId: userInfo?.uid,
        autherid: userInfo?.uid,
        ...config.params
      }
    }
    if (config.method === 'post') {
      config.headers = {
        // ...config.headers,
        'Content-type': 'application/x-www-form-urlencoded'
      }
      config.data = config.data || {}
      config.data = {
        token,
        bundleId: API_HALOLIVE,
        shopId,
        belongId: shopId,
        uid: userInfo?.uid,
        ...config.data
      }
    }
    return config
  },
  (error: { message: any }) => {
    // Do something with request error
    ElMessage.error({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    Promise.reject(error)
  }
)

service.interceptors.response.use(
  (response) => {
    const code = response.data.code
    if ([0, 200].indexOf(code) > -1) {
      // 返回正常
      return response
    } else if (code === 90001) {
      // 用户没有权限
      ElMessage.error({
        message: '您没有操作权限, 请刷新页面重试',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject({
        // 保持结构和error的一致 可以在业务里面统一处理
        message: response.data.msg,
        response
      })
    } else {
      ElMessage.error({
        message: response.data.msg || '接口响应信息异常',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject({
        message: response.data.msg,
        response
      })
    }
  },
  (error) => {
    const message = error.response && error.response.data && error.response.data.message
    ElMessage.error({
      message: message || '网络超时',
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
